/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package bzimerman.media.myflix;


import java.io.FileInputStream;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.Toast;


public class myMediaPlayer extends Activity implements
        OnBufferingUpdateListener, OnCompletionListener,
        OnPreparedListener, OnVideoSizeChangedListener, 
        SurfaceHolder.Callback  {

    private static final String TAG = "MediaPlayerDemo";
    private int mVideoWidth;
    private int mVideoHeight;
    private int sVideoWidth;
    private int sVideoHeight;
    private MediaPlayer mMediaPlayer;
    private SurfaceView mPreview;
    private SurfaceHolder holder;
    private String extras;
    private boolean mIsVideoSizeKnown = false;
    private boolean mIsVideoReadyToBePlayed = false;
    private boolean adjusted = false;
    Display display;

    /**
     * 
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mediaplayer);
        mPreview = (SurfaceView) findViewById(R.id.surface);
        //mPreview = new SurfaceView();
        holder = mPreview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        display = getWindowManager().getDefaultDisplay();
        extras = getIntent().getExtras().getString("PATH_ID");
        
        

    }

    private void playVideo(String Media) {
        doCleanUp();
        try {

            // Create a new media player and set the listeners
            mMediaPlayer = new MediaPlayer();
            
            FileInputStream fileInputStream = new FileInputStream(Media);
            
            Log.d(TAG, "settingDataSource");
            mMediaPlayer.setDataSource(fileInputStream.getFD());
            Log.d(TAG, "dataSourceSet");
            mMediaPlayer.setDisplay(holder);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnBufferingUpdateListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnVideoSizeChangedListener(this);
            //mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);


        } catch (Exception e) {
            Log.e(TAG, "error: " + e.getMessage(), e);
        }
    }

    public void onBufferingUpdate(MediaPlayer arg0, int percent) {
        Log.d(TAG, "onBufferingUpdate percent:" + percent);

    }

    public void onCompletion(MediaPlayer arg0) {
        Log.d(TAG, "onCompletion called");
    }

    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        Log.v(TAG, "onVideoSizeChanged called");
        if (width == 0 || height == 0) {
            Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
            return;
        }
        if (!adjusted){
        	mIsVideoSizeKnown = true;
        	mVideoWidth = width;
        	mVideoHeight = height;
        	sVideoWidth = mVideoWidth;
        	sVideoHeight = mVideoHeight;
        }
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void onPrepared(MediaPlayer mediaplayer) {
        Log.d(TAG, "onPrepared called");
        mIsVideoReadyToBePlayed = true;
        if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
            startVideoPlayback();
        }
    }

    public void surfaceChanged(SurfaceHolder surfaceholder, int format, int width, int height) {
        Log.d(TAG, "surfaceChanged called");
    }

    public void surfaceDestroyed(SurfaceHolder surfaceholder) {
        Log.d(TAG, "surfaceDestroyed called");
    }


    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceCreated called");
        playVideo(extras);


    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaPlayer();
        doCleanUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        doCleanUp();
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    private void doCleanUp() {
        mVideoWidth = 0;
        mVideoHeight = 0;
        mIsVideoReadyToBePlayed = false;
        mIsVideoSizeKnown = false;
    }

    private void startVideoPlayback() {
        Log.v(TAG, "startVideoPlayback");
        if (display.getWidth() > mVideoWidth){
        	holder.setFixedSize(display.getWidth(), display.getHeight());
        }else{
        	holder.setFixedSize(mVideoWidth, mVideoHeight);
        }
        //android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(mVideoWidth*2, mVideoHeight*2);
        //mPreview.setLayoutParams(params);
        //holder.
        Log.v(TAG, "resizeDone");
        mMediaPlayer.start();
    }

    @Override
    /**
     * Overrides the callback method for a UI control handling a Movie
     **/
    public boolean onKeyDown(int keyCode, KeyEvent event) {

      /*
       * Chooses the action to take, based on the incoming keycode
       */
      switch (keyCode) {
        case KeyEvent.KEYCODE_MEDIA_PAUSE:
             
          Log.d("MediaPlayer", "Pausing the Movie");

          if (mMediaPlayer.isPlaying()) {
        	  mMediaPlayer.pause();
          }else{
        	  mMediaPlayer.start();
          }

          return true;

        case KeyEvent.KEYCODE_MEDIA_PLAY:
             
          Log.d("MediaPlayer", "Resuming the Movie");
             
          if (!mMediaPlayer.isPlaying()) {
        	  mMediaPlayer.start();
          }

          
          
          return true;
          
        case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
            
            Log.d("MediaPlayer", "Fast Forwarding the Movie");
               
          	mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition()+30000);

            
            
            return true;
            
        case KeyEvent.KEYCODE_MEDIA_REWIND:
            
            Log.d("MediaPlayer", "Rewinding the Movie");
               
            mMediaPlayer.seekTo(mMediaPlayer.getCurrentPosition()-20000);

            
            
            return true;
            
        case KeyEvent.KEYCODE_Q:
               
            Toast toast = Toast.makeText(getBaseContext(), "Video Dimensions = " + mVideoWidth + " : " + mVideoHeight
            		+ "    Original Dimensions = " + sVideoWidth + " : " + sVideoHeight, Toast.LENGTH_LONG);
            toast.show();

        case KeyEvent.KEYCODE_G:
            
        	adjusted = true;
        	mVideoWidth -= 5;
        	holder.setFixedSize(mVideoWidth, mVideoHeight);
            
            return true;
            
        case KeyEvent.KEYCODE_J:
            
        	adjusted = true;
        	mVideoWidth += 5;
        	holder.setFixedSize(mVideoWidth, mVideoHeight);
            
            return true;
            
        case KeyEvent.KEYCODE_Y:
            
        	adjusted = true;
        	mVideoHeight -= 5;
        	holder.setFixedSize(mVideoWidth, mVideoHeight);
            
            return true;
            
        case KeyEvent.KEYCODE_H:
            
        	adjusted = true;
        	mVideoHeight += 5;
        	holder.setFixedSize(mVideoWidth, mVideoHeight);
            
            return true;

        /*
         * Keycodes should always be passed upwards in the chain for handling.
         */
        default:
          return super.onKeyDown(keyCode, event);
      }
    }
    
}

